import React, { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import { toast } from '@/components/ui/use-toast';
import { 
  Edit, Trash2, Download, Upload, Share2, Settings, Code, 
  Eye, Play, PauseCircle, Clock, Users, Zap, ChevronLeft, 
  ChevronRight, GitBranch, Save, Terminal, Cpu, Database, 
  RefreshCcw, AlertCircle, PlusCircle, FileText, BarChart2
} from 'lucide-react';

// 项目类型定义
interface Project {
  id: string;
  name: string;
  description: string;
  status: 'active' | 'inactive' | 'draft';
  modelType: 'vision' | 'text' | 'multimodal' | 'audio';
  createdAt: string;
  lastUpdated: string;
  isPublic: boolean;
  owner: {
    id: string;
    name: string;
    avatar: string;
  };
  collaborators: Array<{
    id: string;
    name: string;
    avatar: string;
    role: 'editor' | 'viewer';
  }>;
  files: Array<{
    id: string;
    name: string;
    type: string;
    size: number;
    path: string;
    createdAt: string;
    isMain: boolean;
  }>;
  metrics: {
    inferenceCount: number;
    latency: number;
    memoryUsage: number;
    cpuUsage: number;
  };
  deployment: {
    endpoint: string | null;
    status: 'deployed' | 'deploying' | 'failed' | 'not_deployed';
    lastDeployment: string | null;
    replicas: number;
    memory: string;
    cpu: string;
  };
}

// 模拟数据生成函数
const generateMockProject = (id: string): Project => {
  const modelTypes = ['vision', 'text', 'multimodal', 'audio'] as const;
  const statuses = ['active', 'inactive', 'draft'] as const;
  const randomType = modelTypes[Math.floor(Math.random() * modelTypes.length)];
  const randomStatus = statuses[Math.floor(Math.random() * statuses.length)];
  
  return {
    id,
    name: `AI 项目 #${Math.floor(Math.random() * 1000)}`,
    description: `这是一个${randomType === 'vision' ? '视觉' : randomType === 'text' ? '文本' : randomType === 'multimodal' ? '多模态' : '音频'}模型项目的详细描述。该项目用于演示 AI 模型的管理和部署功能。`,
    status: randomStatus,
    modelType: randomType,
    createdAt: new Date(Date.now() - Math.random() * 30 * 86400000).toISOString(),
    lastUpdated: new Date(Date.now() - Math.random() * 7 * 86400000).toISOString(),
    isPublic: Math.random() > 0.5,
    owner: {
      id: 'user-1',
      name: '张开发',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=user1'
    },
    collaborators: Array.from({ length: Math.floor(Math.random() * 3) + 1 }, (_, i) => ({
      id: `user-${i + 2}`,
      name: `协作者 ${i + 1}`,
      avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=user${i + 2}`,
      role: Math.random() > 0.5 ? 'editor' : 'viewer'
    })),
    files: [
      {
        id: 'file-1',
        name: 'model.py',
        type: 'python',
        size: 24560,
        path: '/models/main.py',
        createdAt: new Date(Date.now() - Math.random() * 5 * 86400000).toISOString(),
        isMain: true
      },
      {
        id: 'file-2',
        name: 'requirements.txt',
        type: 'text',
        size: 540,
        path: '/models/requirements.txt',
        createdAt: new Date(Date.now() - Math.random() * 5 * 86400000).toISOString(),
        isMain: false
      },
      {
        id: 'file-3',
        name: 'config.yaml',
        type: 'yaml',
        size: 1200,
        path: '/models/config.yaml',
        createdAt: new Date(Date.now() - Math.random() * 5 * 86400000).toISOString(),
        isMain: false
      },
      ...(randomType === 'vision' ? [
        {
          id: 'file-4',
          name: 'model.onnx',
          type: 'onnx',
          size: 12500000,
          path: '/models/model.onnx',
          createdAt: new Date(Date.now() - Math.random() * 5 * 86400000).toISOString(),
          isMain: false
        }
      ] : [])
    ],
    metrics: {
      inferenceCount: Math.floor(Math.random() * 10000),
      latency: Math.random() * 1000,
      memoryUsage: Math.random() * 2048,
      cpuUsage: Math.random() * 100
    },
    deployment: {
      endpoint: Math.random() > 0.3 ? `https://api.visualdlhub.com/v1/projects/${id}/infer` : null,
      status: Math.random() > 0.3 ? 'deployed' : Math.random() > 0.5 ? 'failed' : 'not_deployed',
      lastDeployment: Math.random() > 0.3 ? new Date(Date.now() - Math.random() * 2 * 86400000).toISOString() : null,
      replicas: Math.floor(Math.random() * 3) + 1,
      memory: `${Math.floor(Math.random() * 3) + 1}Gi`,
      cpu: `${Math.floor(Math.random() * 3) + 1}U`
    }
  };
};

// 模拟性能指标数据
const generatePerformanceData = () => {
  const days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
  return days.map(day => ({
    name: day,
    推理次数: Math.floor(Math.random() * 1000) + 500,
    平均延迟: Math.floor(Math.random() * 500) + 100
  }));
};

// 模拟资源使用数据
const generateResourceData = () => {
  return [
    {
      name: '内存',
      value: Math.floor(Math.random() * 60) + 20
    },
    {
      name: 'CPU',
      value: Math.floor(Math.random() * 70) + 10
    },
    {
      name: 'GPU',
      value: Math.floor(Math.random() * 50) + 5
    }
  ];
};

const ProjectDetailPage = () => {
  const params = useParams();
  const router = useRouter();
  const projectId = params.id as string;
  
  const [project, setProject] = useState<Project | null>(null);
  const [loading, setLoading] = useState(true);
  const [isEditing, setIsEditing] = useState(false);
  const [editForm, setEditForm] = useState({
    name: '',
    description: '',
    status: 'active' as 'active' | 'inactive' | 'draft',
    isPublic: false
  });
  const [performanceData, setPerformanceData] = useState(generatePerformanceData());
  const [resourceData, setResourceData] = useState(generateResourceData());
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [activeTab, setActiveTab] = useState('overview');
  const [isDeploying, setIsDeploying] = useState(false);
  const [isUploading, setIsUploading] = useState(false);

  // 模拟获取项目数据
  useEffect(() => {
    const fetchProject = async () => {
      try {
        setLoading(true);
        // 在实际应用中，这里会调用后端API获取项目详情
        // 模拟网络请求延迟
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // 使用模拟数据
        const mockProject = generateMockProject(projectId);
        setProject(mockProject);
        setEditForm({
          name: mockProject.name,
          description: mockProject.description,
          status: mockProject.status,
          isPublic: mockProject.isPublic
        });
      } catch (error) {
        console.error('获取项目详情失败:', error);
        toast({ title: '获取项目失败', description: '请稍后重试', variant: 'destructive' });
      } finally {
        setLoading(false);
      }
    };

    fetchProject();
  }, [projectId]);

  // 处理编辑项目信息
  const handleSaveEdit = async () => {
    if (!project) return;

    try {
      // 在实际应用中，这里会调用后端API更新项目信息
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const updatedProject = {
        ...project,
        ...editForm,
        lastUpdated: new Date().toISOString()
      };
      
      setProject(updatedProject);
      setIsEditing(false);
      toast({ title: '项目已更新', description: '项目信息已成功保存' });
    } catch (error) {
      console.error('更新项目失败:', error);
      toast({ title: '更新失败', description: '请稍后重试', variant: 'destructive' });
    }
  };

  // 处理部署项目
  const handleDeploy = async () => {
    if (!project) return;

    try {
      setIsDeploying(true);
      // 在实际应用中，这里会调用后端API部署项目
      await new Promise(resolve => setTimeout(resolve, 3000));
      
      const deployedProject = {
        ...project,
        deployment: {
          ...project.deployment,
          status: 'deployed' as const,
          endpoint: `https://api.visualdlhub.com/v1/projects/${projectId}/infer`,
          lastDeployment: new Date().toISOString()
        }
      };
      
      setProject(deployedProject);
      toast({ title: '部署成功', description: '项目已成功部署' });
    } catch (error) {
      console.error('部署失败:', error);
      toast({ title: '部署失败', description: '请稍后重试', variant: 'destructive' });
    } finally {
      setIsDeploying(false);
    }
  };

  // 处理停止部署
  const handleStopDeployment = async () => {
    if (!project) return;

    try {
      // 在实际应用中，这里会调用后端API停止部署
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const updatedProject = {
        ...project,
        deployment: {
          ...project.deployment,
          status: 'not_deployed' as const,
          endpoint: null
        }
      };
      
      setProject(updatedProject);
      toast({ title: '已停止部署', description: '项目部署已停止' });
    } catch (error) {
      console.error('停止部署失败:', error);
      toast({ title: '操作失败', description: '请稍后重试', variant: 'destructive' });
    }
  };

  // 处理删除项目
  const handleDelete = async () => {
    try {
      // 在实际应用中，这里会调用后端API删除项目
      await new Promise(resolve => setTimeout(resolve, 500));
      
      toast({ title: '项目已删除', description: '项目已成功删除' });
      router.push('/projects');
    } catch (error) {
      console.error('删除项目失败:', error);
      toast({ title: '删除失败', description: '请稍后重试', variant: 'destructive' });
    } finally {
      setIsDeleteDialogOpen(false);
    }
  };

  // 处理文件上传
  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files || files.length === 0) return;

    setIsUploading(true);
    
    // 模拟文件上传
    setTimeout(() => {
      setIsUploading(false);
      toast({ title: '文件上传成功', description: `${files.length} 个文件已上传` });
      // 重置input
      e.target.value = '';
    }, 1500);
  };

  // 格式化日期
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return new Intl.DateTimeFormat('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    }).format(date);
  };

  // 格式化文件大小
  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 获取状态对应的徽章颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'active':
        return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400';
      case 'inactive':
        return 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-400';
      case 'draft':
        return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400';
      case 'deployed':
        return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400';
      case 'deploying':
        return 'bg-indigo-100 text-indigo-800 dark:bg-indigo-900/30 dark:text-indigo-400';
      case 'failed':
        return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400';
      case 'not_deployed':
        return 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-400';
      default:
        return 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-400';
    }
  };

  // 获取模型类型对应的标签
  const getModelTypeLabel = (type: string) => {
    switch (type) {
      case 'vision':
        return '视觉';
      case 'text':
        return '文本';
      case 'multimodal':
        return '多模态';
      case 'audio':
        return '音频';
      default:
        return type;
    }
  };

  // 图表颜色
  const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
        <div className="flex flex-col items-center">
          <div className="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin" />
          <p className="mt-4 text-gray-500 dark:text-gray-400">加载项目详情中...</p>
        </div>
      </div>
    );
  }

  if (!project) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900 p-4">
        <div className="text-center max-w-md">
          <div className="w-16 h-16 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center mx-auto mb-4">
            <AlertCircle className="h-8 w-8 text-red-500 dark:text-red-400" />
          </div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">项目不存在</h1>
          <p className="text-gray-500 dark:text-gray-400 mb-6">
            无法找到ID为 {projectId} 的项目，可能该项目已被删除或您没有访问权限。
          </p>
          <Button 
            className="bg-primary hover:bg-primary/90 text-white"
            onClick={() => router.push('/projects')}
          >
            返回项目列表
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900">
      {/* 顶部导航栏 */}
      <header className="sticky top-0 z-30 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 shadow-sm">
        <div className="container mx-auto px-4">
          <div className="flex h-16 items-center justify-between">
            <div className="flex items-center space-x-2">
              <Button 
                variant="ghost" 
                size="icon" 
                className="md:hidden"
                onClick={() => router.back()}
              >
                <ChevronLeft className="h-5 w-5" />
              </Button>
              <h1 className="text-lg font-semibold text-gray-900 dark:text-white truncate">
                {project.name}
              </h1>
              <Badge className={getStatusColor(project.status)}>
                {project.status === 'active' ? '活跃' : project.status === 'inactive' ? '非活跃' : '草稿'}
              </Badge>
            </div>
            
            <div className="flex items-center space-x-2">
              {isEditing ? (
                <>
                  <Button 
                    variant="ghost" 
                    onClick={() => {
                      setIsEditing(false);
                      setEditForm({
                        name: project.name,
                        description: project.description,
                        status: project.status,
                        isPublic: project.isPublic
                      });
                    }}
                  >
                    取消
                  </Button>
                  <Button 
                    className="bg-primary hover:bg-primary/90 text-white"
                    onClick={handleSaveEdit}
                  >
                    <Save className="h-4 w-4 mr-2" />
                    保存
                  </Button>
                </>
              ) : (
                <>
                  <Button 
                    variant="ghost" 
                    className="hidden md:flex"
                    onClick={() => router.push('/projects')}
                  >
                    <ChevronLeft className="h-4 w-4 mr-2" />
                    返回列表
                  </Button>
                  
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button 
                        variant="ghost" 
                        className="text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white"
                      >
                        <Share2 className="h-4 w-4 mr-2" />
                        分享
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                      <DropdownMenuLabel>分享选项</DropdownMenuLabel>
                      <DropdownMenuSeparator />
                      <DropdownMenuItem>
                        复制链接
                      </DropdownMenuItem>
                      <DropdownMenuItem>
                        邀请协作者
                      </DropdownMenuItem>
                      <DropdownMenuSeparator />
                      <DropdownMenuItem>
                        生成嵌入代码
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                  
                  <Button 
                    variant="ghost" 
                    className="text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white"
                    onClick={() => setIsEditing(true)}
                  >
                    <Edit className="h-4 w-4 mr-2" />
                    编辑
                  </Button>
                  
                  <Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
                    <DialogTrigger asChild>
                      <Button 
                        variant="ghost" 
                        className="text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-950/30"
                      >
                        <Trash2 className="h-4 w-4 mr-2" />
                        删除
                      </Button>
                    </DialogTrigger>
                    <DialogContent className="sm:max-w-md">
                      <DialogHeader>
                        <DialogTitle className="text-red-600 dark:text-red-400">删除项目</DialogTitle>
                        <DialogDescription>
                          此操作无法撤销。删除后，项目的所有数据将被永久移除。
                        </DialogDescription>
                      </DialogHeader>
                      
                      <div className="py-4">
                        <div className="flex items-center justify-center p-4 bg-red-50 dark:bg-red-950/30 rounded-md">
                          <AlertCircle className="h-8 w-8 text-red-500 dark:text-red-400" />
                        </div>
                        <p className="mt-4 text-center text-gray-500 dark:text-gray-400">
                          确定要删除项目 "<span className="font-medium text-gray-900 dark:text-white">{project.name}</span>" 吗？
                        </p>
                      </div>
                      
                      <DialogFooter>
                        <Button variant="ghost" onClick={() => setIsDeleteDialogOpen(false)}>
                          取消
                        </Button>
                        <Button 
                          className="bg-red-600 hover:bg-red-700 text-white"
                          onClick={handleDelete}
                        >
                          删除
                        </Button>
                      </DialogFooter>
                    </DialogContent>
                  </Dialog>
                </>
              )}
            </div>
          </div>
        </div>
      </header>

      <main className="container mx-auto px-4 py-6">
        {/* 项目基本信息 */}
        <Card className="mb-6 border border-gray-200 dark:border-gray-700">
          <CardHeader className="pb-3">
            {isEditing ? (
              <>
                <Input
                  placeholder="项目名称"
                  className="text-xl font-bold mb-2"
                  value={editForm.name}
                  onChange={(e) => setEditForm({...editForm, name: e.target.value})}
                />
                <Select 
                  value={editForm.status}
                  onValueChange={(value) => setEditForm({...editForm, status: value as 'active' | 'inactive' | 'draft'})}
                >
                  <SelectTrigger className="w-[180px] mb-2">
                    <SelectValue placeholder="项目状态" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="active">活跃</SelectItem>
                    <SelectItem value="inactive">非活跃</SelectItem>
                    <SelectItem value="draft">草稿</SelectItem>
                  </SelectContent>
                </Select>
              </>
            ) : (
              <CardTitle className="text-2xl">{project.name}</CardTitle>
            )}
          </CardHeader>
          <CardContent className="pb-4">
            {isEditing ? (
              <Textarea
                placeholder="项目描述"
                className="resize-none mb-4"
                rows={3}
                value={editForm.description}
                onChange={(e) => setEditForm({...editForm, description: e.target.value})}
              />
            ) : (
              <CardDescription className="text-base text-gray-600 dark:text-gray-300 mb-4">
                {project.description}
              </CardDescription>
            )}
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
              <div className="flex items-center space-x-4">
                <div className="w-10 h-10 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center">
                  <FileText className="h-5 w-5 text-gray-500 dark:text-gray-400" />
                </div>
                <div>
                  <p className="text-sm text-gray-500 dark:text-gray-400">模型类型</p>
                  <p className="font-medium">{getModelTypeLabel(project.modelType)}</p>
                </div>
              </div>
              
              <div className="flex items-center space-x-4">
                <div className="w-10 h-10 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center">
                  <Clock className="h-5 w-5 text-gray-500 dark:text-gray-400" />
                </div>
                <div>
                  <p className="text-sm text-gray-500 dark:text-gray-400">创建时间</p>
                  <p className="font-medium">{formatDate(project.createdAt)}</p>
                </div>
              </div>
              
              <div className="flex items-center space-x-4">
                <div className="w-10 h-10 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center">
                  <RefreshCcw className="h-5 w-5 text-gray-500 dark:text-gray-400" />
                </div>
                <div>
                  <p className="text-sm text-gray-500 dark:text-gray-400">最后更新</p>
                  <p className="font-medium">{formatDate(project.lastUpdated)}</p>
                </div>
              </div>
              
              <div className="flex items-center space-x-4">
                <div className="w-10 h-10 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center">
                  <Users className="h-5 w-5 text-gray-500 dark:text-gray-400" />
                </div>
                <div>
                  <p className="text-sm text-gray-500 dark:text-gray-400">协作者</p>
                  <div className="flex -space-x-2 mt-1">
                    <Avatar className="border-2 border-white dark:border-gray-800 w-7 h-7">
                      <AvatarImage src={project.owner.avatar} />
                      <AvatarFallback>{project.owner.name.charAt(0)}</AvatarFallback>
                    </Avatar>
                    {project.collaborators.slice(0, 3).map(collaborator => (
                      <Avatar key={collaborator.id} className="border-2 border-white dark:border-gray-800 w-7 h-7">
                        <AvatarImage src={collaborator.avatar} />
                        <AvatarFallback>{collaborator.name.charAt(0)}</AvatarFallback>
                      </Avatar>
                    ))}
                    {project.collaborators.length > 3 && (
                      <div className="w-7 h-7 rounded-full bg-gray-200 dark:bg-gray-700 border-2 border-white dark:border-gray-800 flex items-center justify-center text-xs font-medium">
                        +{project.collaborators.length - 3}
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>
            
            <div className="flex items-center space-x-2">
              <Switch 
                id="public-switch"
                checked={isEditing ? editForm.isPublic : project.isPublic}
                onCheckedChange={(checked) => isEditing && setEditForm({...editForm, isPublic: checked})}
                disabled={!isEditing}
              />
              <Label htmlFor="public-switch" className="font-medium">
                公开项目
              </Label>
            </div>
          </CardContent>
        </Card>

        {/* 项目部署状态卡片 */}
        <Card className="mb-6 border border-gray-200 dark:border-gray-700">
          <CardHeader className="pb-2">
            <div className="flex items-center justify-between">
              <CardTitle className="text-lg">部署状态</CardTitle>
              {project.deployment.status === 'deployed' && (
                <Button 
                  variant="ghost" 
                  className="text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-950/30"
                  onClick={handleStopDeployment}
                >
                  <PauseCircle className="h-4 w-4 mr-2" />
                  停止部署
                </Button>
              )}
              {(project.deployment.status === 'not_deployed' || project.deployment.status === 'failed') && (
                <Button 
                  className="bg-primary hover:bg-primary/90 text-white"
                  onClick={handleDeploy}
                  disabled={isDeploying}
                >
                  {isDeploying ? (
                    <div className="flex items-center space-x-2">
                      <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                      <span>部署中...</span>
                    </div>
                  ) : (
                    <>
                      <Play className="h-4 w-4 mr-2" />
                      部署项目
                    </>
                  )}
                </Button>
              )}
            </div>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="bg-gray-50 dark:bg-gray-800/50 p-4 rounded-lg">
                <p className="text-sm text-gray-500 dark:text-gray-400 mb-1">部署状态</p>
                <div className="flex items-center space-x-2">
                  <Badge className={getStatusColor(project.deployment.status)}>
                    {project.deployment.status === 'deployed' ? '已部署' : 
                     project.deployment.status === 'deploying' ? '部署中' : 
                     project.deployment.status === 'failed' ? '部署失败' : '未部署'}
                  </Badge>
                  {project.deployment.status === 'failed' && (
                    <Button variant="ghost" size="icon" className="h-6 w-6 text-gray-500">
                      <AlertCircle className="h-3 w-3" />
                    </Button>
                  )}
                </div>
              </div>
              
              <div className="bg-gray-50 dark:bg-gray-800/50 p-4 rounded-lg">
                <p className="text-sm text-gray-500 dark:text-gray-400 mb-1">API 端点</p>
                {project.deployment.endpoint ? (
                  <div className="flex items-center space-x-2">
                    <Code className="h-4 w-4 text-gray-500" />
                    <span className="font-mono text-sm break-all">{project.deployment.endpoint}</span>
                  </div>
                ) : (
                  <span className="text-gray-400">暂无</span>
                )}
              </div>
              
              <div className="bg-gray-50 dark:bg-gray-800/50 p-4 rounded-lg">
                <p className="text-sm text-gray-500 dark:text-gray-400 mb-1">最后部署时间</p>
                {project.deployment.lastDeployment ? (
                  <div className="flex items-center space-x-2">
                    <Clock className="h-4 w-4 text-gray-500" />
                    <span>{formatDate(project.deployment.lastDeployment)}</span>
                  </div>
                ) : (
                  <span className="text-gray-400">暂无</span>
                )}
              </div>
            </div>
            
            {project.deployment.status === 'deployed' && (
              <div className="mt-4 bg-blue-50 dark:bg-blue-950/30 p-4 rounded-lg border border-blue-100 dark:border-blue-900/30">
                <div className="flex items-start space-x-3">
                  <Terminal className="h-5 w-5 text-blue-500 dark:text-blue-400 mt-0.5" />
                  <div>
                    <h4 className="font-medium text-blue-800 dark:text-blue-300 mb-1">调用示例</h4>
                    <pre className="bg-gray-900 text-gray-100 p-3 rounded-md text-sm overflow-x-auto">
                      <code>
                        {`curl -X POST ${project.deployment.endpoint}\n  -H "Content-Type: application/json"\n  -d '{"input": "your_input_here"}'`}
                      </code>
                    </pre>
                  </div>
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* 选项卡内容 */}
        <Tabs defaultValue="overview" value={activeTab} onValueChange={setActiveTab} className="space-y-6">
          <TabsList className="grid w-full md:w-auto md:inline-grid grid-cols-4">
            <TabsTrigger value="overview" className="data-[state=active]:bg-primary data-[state=active]:text-white">
              <BarChart2 className="h-4 w-4 mr-2" />
              概览
            </TabsTrigger>
            <TabsTrigger value="files" className="data-[state=active]:bg-primary data-[state=active]:text-white">
              <FileText className="h-4 w-4 mr-2" />
              文件
            </TabsTrigger>
            <TabsTrigger value="settings" className="data-[state=active]:bg-primary data-[state=active]:text-white">
              <Settings className="h-4 w-4 mr-2" />
              设置
            </TabsTrigger>
            <TabsTrigger value="collaborators" className="data-[state=active]:bg-primary data-[state=active]:text-white">
              <Users className="h-4 w-4 mr-2" />
              协作者
            </TabsTrigger>
          </TabsList>

          {/* 概览选项卡 */}
          <TabsContent value="overview" className="space-y-6">
            {/* 性能指标卡片 */}
            <Card className="border border-gray-200 dark:border-gray-700">
              <CardHeader className="pb-2">
                <CardTitle className="text-lg">性能指标</CardTitle>
                <CardDescription>项目推理性能和资源使用情况</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="h-72">
                    <h4 className="text-sm font-medium text-gray-500 dark:text-gray-400 mb-3">每周性能趋势</h4>
                    <ResponsiveContainer width="100%" height="85%">
                      <BarChart data={performanceData} margin={{ top: 5, right: 20, bottom: 5, left: 0 }}>
                        <CartesianGrid strokeDasharray="3 3" stroke="rgba(0,0,0,0.1)" />
                        <XAxis dataKey="name" fontSize={12} tickMargin={8} />
                        <YAxis fontSize={12} />
                        <Tooltip 
                          contentStyle={{ 
                            backgroundColor: '#fff', 
                            border: '1px solid #e2e8f0', 
                            borderRadius: '0.375rem',
                            boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)'
                          }}
                        />
                        <Bar dataKey="推理次数" fill="#3b82f6" radius={[4, 4, 0, 0]} />
                        <Bar dataKey="平均延迟" fill="#10b981" radius={[4, 4, 0, 0]} />
                      </BarChart>
                    </ResponsiveContainer>
                  </div>
                  
                  <div className="h-72">
                    <h4 className="text-sm font-medium text-gray-500 dark:text-gray-400 mb-3">资源使用情况</h4>
                    <ResponsiveContainer width="100%" height="85%">
                      <PieChart>
                        <Pie
                          data={resourceData}
                          cx="50%"
                          cy="50%"
                          labelLine={false}
                          outerRadius={80}
                          fill="#8884d8"
                          dataKey="value"
                          label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
                        >
                          {resourceData.map((entry, index) => (
                            <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                          ))}
                        </Pie>
                        <Tooltip formatter={(value) => `${value}%`} />
                      </PieChart>
                    </ResponsiveContainer>
                  </div>
                </div>
                
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mt-6">
                  <div className="bg-gray-50 dark:bg-gray-800/50 p-4 rounded-lg">
                    <p className="text-sm text-gray-500 dark:text-gray-400 mb-1">总推理次数</p>
                    <div className="flex items-center space-x-2">
                      <Zap className="h-5 w-5 text-amber-500" />
                      <p className="text-2xl font-bold">{project.metrics.inferenceCount.toLocaleString()}</p>
                    </div>
                  </div>
                  
                  <div className="bg-gray-50 dark:bg-gray-800/50 p-4 rounded-lg">
                    <p className="text-sm text-gray-500 dark:text-gray-400 mb-1">平均延迟</p>
                    <div className="flex items-center space-x-2">
                      <Clock className="h-5 w-5 text-blue-500" />
                      <p className="text-2xl font-bold">{project.metrics.latency.toFixed(2)} ms</p>
                    </div>
                  </div>
                  
                  <div className="bg-gray-50 dark:bg-gray-800/50 p-4 rounded-lg">
                    <p className="text-sm text-gray-500 dark:text-gray-400 mb-1">内存使用</p>
                    <div className="flex items-center space-x-2">
                      <Database className="h-5 w-5 text-green-500" />
                      <p className="text-2xl font-bold">{project.metrics.memoryUsage.toFixed(1)} MB</p>
                    </div>
                  </div>
                  
                  <div className="bg-gray-50 dark:bg-gray-800/50 p-4 rounded-lg">
                    <p className="text-sm text-gray-500 dark:text-gray-400 mb-1">CPU 使用率</p>
                    <div className="flex items-center space-x-2">
                      <Cpu className="h-5 w-5 text-purple-500" />
                      <p className="text-2xl font-bold">{project.metrics.cpuUsage.toFixed(1)}%</p>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* 文件选项卡 */}
          <TabsContent value="files" className="space-y-6">
            <Card className="border border-gray-200 dark:border-gray-700">
              <CardHeader className="pb-2">
                <div className="flex items-center justify-between">
                  <CardTitle className="text-lg">项目文件</CardTitle>
                  <div className="flex items-center space-x-2">
                    <label htmlFor="file-upload" className="cursor-pointer">
                      <Button 
                        variant="ghost" 
                        className="text-primary hover:bg-primary/10"
                        disabled={isUploading}
                      >
                        {isUploading ? (
                          <div className="flex items-center space-x-2">
                            <div className="w-4 h-4 border-2 border-primary border-t-transparent rounded-full animate-spin" />
                            <span>上传中...</span>
                          </div>
                        ) : (
                          <>
                            <Upload className="h-4 w-4 mr-2" />
                            上传文件
                          </>
                        )}
                      </Button>
                      <input 
                        id="file-upload" 
                        type="file" 
                        multiple 
                        className="hidden"
                        onChange={handleFileUpload}
                        disabled={isUploading}
                      />
                    </label>
                    <Button 
                      variant="ghost" 
                      className="text-gray-600 dark:text-gray-300"
                      disabled={isUploading}
                    >
                      <GitBranch className="h-4 w-4 mr-2" />
                      版本历史
                    </Button>
                  </div>
                </div>
                <CardDescription>管理项目的代码和模型文件</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {project.files.map(file => (
                    <div 
                      key={file.id} 
                      className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
                    >
                      <div className="flex items-center space-x-3">
                        <div className={`w-8 h-8 rounded-md flex items-center justify-center ${file.type === 'python' ? 'bg-blue-100 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400' : file.type === 'text' ? 'bg-green-100 text-green-600 dark:bg-green-900/30 dark:text-green-400' : file.type === 'yaml' ? 'bg-amber-100 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400' : 'bg-purple-100 text-purple-600 dark:bg-purple-900/30 dark:text-purple-400'}`}>
                          <FileText className="h-4 w-4" />
                        </div>
                        <div>
                          <p className="font-medium flex items-center space-x-2">
                            {file.name}
                            {file.isMain && (
                              <Badge variant="secondary" className="bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400 border-0">
                                主文件
                              </Badge>
                            )}
                          </p>
                          <p className="text-sm text-gray-500 dark:text-gray-400">{formatFileSize(file.size)} • {formatDate(file.createdAt)}</p>
                        </div>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Button variant="ghost" size="icon" className="h-8 w-8 text-gray-600 dark:text-gray-300">
                          <Eye className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="icon" className="h-8 w-8 text-gray-600 dark:text-gray-300">
                          <Download className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
                
                <div className="mt-6 p-4 border border-dashed border-gray-300 dark:border-gray-700 rounded-lg text-center">
                  <PlusCircle className="h-10 w-10 text-gray-400 mx-auto mb-2" />
                  <p className="text-gray-500 dark:text-gray-400 mb-3">添加新文件</p>
                  <div className="flex flex-wrap justify-center gap-2">
                    <Button variant="outline" size="sm">创建新文件</Button>
                    <Button variant="outline" size="sm">上传文件夹</Button>
                    <Button variant="outline" size="sm">从模板创建</Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* 设置选项卡 */}
          <TabsContent value="settings" className="space-y-6">
            <Card className="border border-gray-200 dark:border-gray-700">
              <CardHeader className="pb-2">
                <CardTitle className="text-lg">部署配置</CardTitle>
                <CardDescription>配置项目的部署参数和资源分配</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="replicas">副本数量</Label>
                      <Select defaultValue={project.deployment.replicas.toString()}>
                        <SelectTrigger id="replicas">
                          <SelectValue placeholder="选择副本数量" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="1">1 个副本</SelectItem>
                          <SelectItem value="2">2 个副本</SelectItem>
                          <SelectItem value="3">3 个副本</SelectItem>
                          <SelectItem value="5">5 个副本</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    
                    <div className="space-y-2">
                      <Label htmlFor="memory">内存分配</Label>
                      <Select defaultValue={project.deployment.memory}>
                        <SelectTrigger id="memory">
                          <SelectValue placeholder="选择内存大小" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="1Gi">1 GB</SelectItem>
                          <SelectItem value="2Gi">2 GB</SelectItem>
                          <SelectItem value="4Gi">4 GB</SelectItem>
                          <SelectItem value="8Gi">8 GB</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    
                    <div className="space-y-2">
                      <Label htmlFor="cpu">CPU 分配</Label>
                      <Select defaultValue={project.deployment.cpu}>
                        <SelectTrigger id="cpu">
                          <SelectValue placeholder="选择 CPU 数量" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="1U">1 核心</SelectItem>
                          <SelectItem value="2U">2 核心</SelectItem>
                          <SelectItem value="4U">4 核心</SelectItem>
                          <SelectItem value="8U">8 核心</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    
                    <div className="space-y-2">
                      <Label htmlFor="gpu">GPU 分配</Label>
                      <Select defaultValue="none">
                        <SelectTrigger id="gpu">
                          <SelectValue placeholder="选择 GPU 类型" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="none">无 GPU</SelectItem>
                          <SelectItem value="t4">NVIDIA T4</SelectItem>
                          <SelectItem value="v100">NVIDIA V100</SelectItem>
                          <SelectItem value="a100">NVIDIA A100</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                  
                  <div className="space-y-2">
                    <Label htmlFor="environment-variables">环境变量</Label>
                    <Textarea
                      id="environment-variables"
                      placeholder="KEY=value\nANOTHER_KEY=another_value"
                      className="resize-none"
                      rows={4}
                    />
                  </div>
                  
                  <div className="space-y-2">
                    <Label htmlFor="custom-domain">自定义域名</Label>
                    <Input
                      id="custom-domain"
                      placeholder="model.yourdomain.com"
                      disabled={project.deployment.status !== 'deployed'}
                    />
                    {project.deployment.status !== 'deployed' && (
                      <p className="text-xs text-gray-500 dark:text-gray-400">部署项目后可设置自定义域名</p>
                    )}
                  </div>
                </div>
                
                <div className="mt-6">
                  <Button className="bg-primary hover:bg-primary/90 text-white">
                    <Save className="h-4 w-4 mr-2" />
                    保存配置
                  </Button>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* 协作者选项卡 */}
          <TabsContent value="collaborators" className="space-y-6">
            <Card className="border border-gray-200 dark:border-gray-700">
              <CardHeader className="pb-2">
                <div className="flex items-center justify-between">
                  <CardTitle className="text-lg">协作者</CardTitle>
                  <Button 
                    className="bg-primary hover:bg-primary/90 text-white"
                  >
                    <Plus className="h-4 w-4 mr-2" />
                    邀请协作者
                  </Button>
                </div>
                <CardDescription>管理项目的协作者和权限</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-800/50 rounded-lg border-l-4 border-primary">
                    <div className="flex items-center space-x-3">
                      <Avatar className="w-10 h-10">
                        <AvatarImage src={project.owner.avatar} />
                        <AvatarFallback>{project.owner.name.charAt(0)}</AvatarFallback>
                      </Avatar>
                      <div>
                        <p className="font-medium flex items-center space-x-2">
                          {project.owner.name}
                          <Badge variant="secondary" className="bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400 border-0">
                            所有者
                          </Badge>
                        </p>
                        <p className="text-sm text-gray-500 dark:text-gray-400">创建于 {formatDate(project.createdAt)}</p>
                      </div>
                    </div>
                    <span className="text-gray-500 dark:text-gray-400">全部权限</span>
                  </div>
                  
                  {project.collaborators.map(collaborator => (
                    <div 
                      key={collaborator.id} 
                      className="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-800/50 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
                    >
                      <div className="flex items-center space-x-3">
                        <Avatar className="w-10 h-10">
                          <AvatarImage src={collaborator.avatar} />
                          <AvatarFallback>{collaborator.name.charAt(0)}</AvatarFallback>
                        </Avatar>
                        <div>
                          <p className="font-medium flex items-center space-x-2">
                            {collaborator.name}
                            <Badge variant="secondary" className="bg-gray-200 text-gray-700 dark:bg-gray-700 dark:text-gray-300 border-0">
                              {collaborator.role === 'editor' ? '编辑者' : '查看者'}
                            </Badge>
                          </p>
                          <Select defaultValue={collaborator.role} className="w-[120px] mt-1">
                            <SelectTrigger className="h-8 text-xs">
                              <SelectValue placeholder="更改角色" />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="editor">编辑者</SelectItem>
                              <SelectItem value="viewer">查看者</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                      </div>
                      <Button variant="ghost" size="icon" className="h-8 w-8 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-950/30">
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </main>
    </div>
  );
};

export default ProjectDetailPage;